package com.bigknow.appstore.web.console.controller;

import com.bigknow.appstore.web.console.app.Application;
import com.bigknow.appstore.web.console.app.ApplicationCategory;
import com.bigknow.appstore.web.console.app.ApplicationState;
import com.bigknow.appstore.web.console.service.IApplicationService;
import com.bigknow.appstore.web.console.service.impl.ApplicationCategoryService;
import com.bigknow.appstore.web.framework.controller.AbstractRestController;
import com.bigknow.appstore.web.framework.vo.Page;
import com.bigknow.appstore.web.framework.vo.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * Created by 李科风 on 2016-10-17.
 */
@RestController
@RequestMapping("/sys/approve")
public class ApplicationApproveController extends AbstractRestController<Application, IApplicationService> {

    @Autowired
    private ApplicationCategoryService applicationCategoryService;

    @Override
    protected String getBasePath() {
        return "sys";
    }

    @Override
    protected String getBaseName() {
        return "approve";
    }

    @RequestMapping(value = "/form/{actionType}/{id}")
    public ModelAndView form(@PathVariable String actionType, @PathVariable String id) {
        ModelAndView mv = super.form(actionType, id);
        mv.setViewName("/console/app/appForm");
        return mv;
    }

    @RequestMapping("/passPublish")
    public ResultInfo passPublish(@RequestParam("id") String id) {
        Application app = service.get(id);
        app.setState(ApplicationState.PUBLISHED);
        return super.update(app);
    }

    @RequestMapping("/rejectPublish")
    public ResultInfo rejectPublish(@RequestParam("id") String id) {
        Application app = service.get(id);
        app.setState(ApplicationState.TEST);
        return super.update(app);
    }

    @RequestMapping(value = "/list")
    public ModelAndView list(Application app, Integer pageIndex, Integer pageSize) {
        if (app.getState() == null) {
            app.setState(ApplicationState.APPLYING);
        }
        ModelAndView mv = super.list(app, pageIndex, pageSize);
        mv.getModel().put("state", app.getState());
        List<Application> apps = ((Page) mv.getModel().get("page")).getEntities();
        for (Application _app : apps) {
            _app.setCategory(applicationCategoryService.getCategory(_app.getCategoryId()));
        }
        return mv;
    }
}
